package com.huxiaoshou.exam.config;

import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class MyThreadFactory implements ThreadFactory {

    private final String threadNamePrefix;

    private final AtomicInteger threadNumber = new AtomicInteger(1);

    private final boolean daemon;

    private final int priority;

    public MyThreadFactory(String threadNamePrefix) {
        this(threadNamePrefix, false, Thread.NORM_PRIORITY);
    }

    public MyThreadFactory(String threadNamePrefix, boolean daemon, int priority) {
        this.threadNamePrefix = threadNamePrefix;
        this.daemon = daemon;
        this.priority = priority;
    }


    @Override
    public Thread newThread(@NotNull Runnable r) {
        Thread t = new Thread(r, threadNamePrefix + "-thread-" + threadNumber.getAndIncrement()) {
            @Override
            public void run() {
                try {
                    super.run();
                } catch (Throwable e) {
                    log.error("线程[{}]执行异常", getName(), e);
                    throw e;
                }
            }
        };

        t.setDaemon(daemon);
        t.setPriority(priority);
        return t;
    }

}
